package com.ys.controller.api.purchase;

import com.ys.config.MenuId;
import com.ys.entity.purchase.TcgPurchaseContract;
import com.ys.entity.sys.YsCol;
import com.ys.service.purchase.TcgPurchaseContractService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 采购合同管理
 */
@Controller
@RequestMapping("/api/inter/tcgPurchaseContractByManage")
public class ApiInterTcgPurchaseContractByManageController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcgPurchaseContractByManageController.class);

    @Autowired
    private CommonApiService<TcgPurchaseContract> commonApiService;

    @Autowired
    private TcgPurchaseContractService tcgPurchaseContractService;

    //菜单id
    private Long menuId = MenuId.TCG_PurchaseContract_ByManage;

    //权限字符
    private final String PERMISSIONS_VIEW = "tcgPurchaseContractByManage:view";
    private final String PERMISSIONS_ADD = "tcgPurchaseContractByManage:cancel";

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcgPurchaseContract setSeachSql(TcgPurchaseContract cond){

        cond
                //.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                //.addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人

                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTime")//审核时间

                //.addLeftJoin("TCG_PurchaseAppointOrder O ON O.Id = A.PurchaseAppointOrderId ")//预约采购管理表
                .addLeftJoin("TB_CompanyInfo CI ON CI.Vid = A.CompanyInfoVid ")//公司信息
                .addField("CI.Vname AS vname")//购买方公司名称
                .addField("CI.Tax AS tax")//公司税号

                //.addLeftJoin("TB_CompanyBankInfo B ON B.Id = A.CompanyBankInfoId ")//公司银行账户管理表
                //.addField("B.Vyhzhmc AS vyhzhmc")//付款户名 、 银行账户名称
                //.addField("B.Vkhh AS vkhh")//付款银行 、 开户行
                //.addField("B.Vyhzh AS vyhzh")//付款银行账户 、 银行账户编码

                .addLeftJoin("TCW_PartnerBankInfo PB ON PB.Id = A.PartnerBankInfoId ")//合作商银行账户管理表
                .addField("PB.PartnerName AS partnerName")//供应方公司名称 、合作方名称
                .addField("PB.Vgssh AS vgssh")//供应方公司税号 、 合作方税号
                .addField("(PB.Vlxr + '&' +  PB.Vgsdh) AS vgsdh")//联系人及方式 、 联系人&联系方式
                .addField("PB.Vyhzhmc AS pbVyhzhmc")//收款户名 、 银行账户名称
                .addField("PB.Vkhh AS pbVkhh")//收款银行 、 开户行
                .addField("PB.Vyhzh AS pbVyhzh")//收款银行账户 、 银行账户编码

                .addLeftJoin("TCG_PurchaseContractItem S ON S.Pbid = A.Bid")//合同单子表
                .addField("S.Id AS itemId")//子表id
                .addField("S.SubBomNumber AS subBomNumber")//子件BOM数量
                .addField("S.SubPurchaseNum AS subPurchaseNum")//子件采购数量
                .addField("S.SubPurchasePrice AS subPurchasePrice")//子件采购单价
                .addField("S.PurchaseTotalPrice AS purchaseTotalPrice")//子件采购总价
                .addField("S.SubPaymentNum AS subPaymentNum")//子件付款数量
                .addField("S.SubWarehousingNum AS subWarehousingNum")//子件入库数量
                .addField("S.SubWriteOffNum AS subWriteOffNum")//子件核销数量
                .addField("S.SubPreWarehousingNum AS subPreWarehousingNum")//子件预入库数量

                .addField("S.SubPaymentState AS subPaymentState")//采购付款完整性（0否、1是）
                .addField("S.SubWarehousingState AS subWarehousingState")//采购入库完整性（0否、1是）
                .addField("S.SubWriteOffState AS subWriteOffState")//采购核销完整性（0否、1是）
                .addField("S.CancelState AS cancelState")//采购取消状态（0取消、1正常）

                .addField("CASE WHEN S.SubPaymentState = 0 THEN '否' ELSE '是' END subPaymentStateTxt")
                .addField("CASE WHEN S.SubWarehousingState = 0 THEN '否' ELSE '是' END subWarehousingStateTxt")
                .addField("CASE WHEN S.SubWriteOffState = 0 THEN '否' ELSE '是' END subWriteOffStateTxt")
                .addField("CASE WHEN S.CancelState = 0 THEN '取消' ELSE '正常' END cancelStateTxt")

                .addLeftJoin("TCG_PurchaseAppointOrderProductComponent C ON C.Id = S.OrderProductComponentId")//预约采购管理子件表
                .addLeftJoin("TCG_PurchaseAppointOrderItem PC ON C.Pid = PC.Id")//预约采购管理母件表
                .addLeftJoin("TCG_PurchaseAppointOrder PPC ON PPC.Bid = PC.Pbid")//预约采购单母表
                .addLeftJoin("THR_OperateCompanyApply OCA ON OCA.Vgsbm = PPC.Vgsbm")//运营公司管理表

                .addField("PPC.Bid AS appointOrderBid")//预约采购单单号
                .addField("PPC.Vgsbm AS vgsbm")//运营公司编码
                .addField("OCA.Vgsjc AS vgsjc")//运营公司简称
                .addField("PC.ProductCode AS productCode")//商品编码
                .addField("PC.ProductName AS productName")//商品名称
                .addField("PC.CodeMerge AS codeMerge")//合并商品编码
                .addField("PC.ReserveNumber AS reserveNumber")//母件预约数量
                .addField("C.SubCode AS subCode")//子件编码
                .addField("C.SubName AS subName")//子件名称
                .addField("C.SubCodeMerge AS subCodeMerge")//子件合并编码
                //.addField("C.SubBomNumber AS subBomNumber")//子件BOM数量
                //.addField("C.SubBomPrice AS subBomPrice")//子件BOM单价
                .addField("C.SubReserveNumber AS subReserveNumber")//子件预约数量

                .setEffectStock(1)

        //排序
        .setOrderby("A.Bid DESC");


        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcgPurchaseContract cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);
            cond = commonApiService.dataAuth(menuId, cond);
            //查询条件
            /*
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
             */
            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcgPurchaseContract cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            cond = commonApiService.dataAuth(menuId, cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TcgPurchaseContract> util = new ExportExcelUtils<>(new TcgPurchaseContract());
            String toFilePath = util.exportExcel(listData, listField, "采购合同管理");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 采购取消
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/cancelInfo")
    @ResponseBody
    public R cancelInfo(HttpServletRequest request, Long itemId,String bid){
        try {
            //采购取消
            return tcgPurchaseContractService.cancelInfo(bid);
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }




    /*
     * 采购合同管理（发票预核销单调用）
     */
    @RequestMapping("/modalByInvoiceOffset")
    @ResponseBody
    public LayuiTableVoJA modalByInvoiceOffset(com.bo.annotation.Model model, HttpServletRequest request, HttpServletResponse response,
                                                     @ModelAttribute TcgPurchaseContract cond
    ) {
        try {

            cond = setSeachSql(cond);

            cond.addLeftJoin("TP_ProductActiveComponent PAC ON PAC.Code = C.SubCode")
                    .addField("PAC.InvoiceModelNo AS invoiceModelNo")//发票型号
                    .addField("PAC.InvoiceName AS invoiceName")//发票品名
                    .where("S.SubWriteOffState !=1 AND S.CancelState = 1");//核销完整性不为是的

            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            return tableVoJA;
        } catch (Exception e) {
            logger.error("查询出错：", e.getMessage(), e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }

    }



}